package com.dynamicthreadpool.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 命名线程工厂，用于创建带有自定义名称的线程
 */
public class NamedThreadFactory implements ThreadFactory {

    private final String prefix;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final boolean daemon;

    /**
     * 构造函数
     * @param prefix 线程名称前缀
     */
    public NamedThreadFactory(String prefix) {
        this(prefix, false);
    }

    /**
     * 构造函数
     * @param prefix 线程名称前缀
     * @param daemon 是否为守护线程
     */
    public NamedThreadFactory(String prefix, boolean daemon) {
        this.prefix = prefix != null ? prefix : "pool-thread";
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, prefix + "-" + threadNumber.getAndIncrement());
        thread.setDaemon(daemon);
        // 设置线程优先级为正常
        thread.setPriority(Thread.NORM_PRIORITY);
        return thread;
    }

    /**
     * 获取线程名称前缀
     * @return 线程名称前缀
     */
    public String getPrefix() {
        return prefix;
    }

    /**
     * 设置线程名称前缀
     * @param newPrefix 新的线程名称前缀
     * @return 新的线程工厂实例
     */
    public NamedThreadFactory withPrefix(String newPrefix) {
        return new NamedThreadFactory(newPrefix, this.daemon);
    }
}
